/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.webanovare.model;

import com.webanovare.model.db.PlayedGame;
import com.webanovare.model.db.User;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 * Handles game informaion for ended games.
 * @author jarmju
 */
@Stateless
public class GamesRegistry extends AbstractDAO<PlayedGame, Long> {
    
    @PersistenceContext(unitName = "webanovare_pu")
    protected EntityManager em;
    
    @EJB
    UserRegistry ur;
    
    public GamesRegistry() {
        super(PlayedGame.class);
    }
    
    @PostConstruct
    public void postConstruct(){
        Logger.getAnonymousLogger().log(Level.INFO, "Alive {0}", this);
        super.setEntitymanager(em);
    }
    
    public List<Integer> getHighScores() {
        List<Integer> scores = new ArrayList<>();
        List<PlayedGame> games = getTopGames(10);
    
        for (PlayedGame p : games) {
            int winnerScore = p.getWinnerPoints();
            scores.add(winnerScore);
        }
        return scores;
    }
    
    public List<String> getTopPlayers() {
        List<String> players = new ArrayList<>();
        List<PlayedGame> games = getTopGames(10);
        
        for (PlayedGame p : games) {
            String awesomePlayer = p.getWinner().getUsername();
            players.add(awesomePlayer);
        }
        return players;
    }
    
    public List<PlayedGame> getTopGames(int n) {
        String high = "select p from PlayedGame p order by p.winnerPoints desc";
        TypedQuery<PlayedGame> tq = em.createQuery(high, PlayedGame.class);
        tq.setMaxResults(n);
        return tq.getResultList();
    }
    
    public List<PlayedGame> getByUser(String name) {
        User user = ur.findUser(name);
        String gameByName = "select p from PlayedGame p where p.owner = :user OR p.opponent = :user";
        TypedQuery<PlayedGame> tq = em.createQuery(gameByName, PlayedGame.class);
        tq.setParameter("user", user);
        return tq.getResultList();
    }
    
    public PlayedGame getById(Long id) {
        String gameById = "select p from PlayedGame p where p.id = :id";
        TypedQuery<PlayedGame> tq = em.createQuery(gameById, PlayedGame.class);
        tq.setParameter("id", id);
        if (tq.getResultList().size() == 1)
            return tq.getResultList().get(0);
        return null;
    }
    
    @Override
    public List<PlayedGame> getAll() {
        return super.getAll();
    }
}
